<?php


namespace broadcast\services;

use app\models\system\SystemWebsite;
use broadcast\redis\setRedis;


use EasyWeChat\Factory;
//reids 记录
class WechatServices
{
    private static $instance = null;
    private $info = [
        'type' => ''
    ];
    public function __construct($info) 
    {
        $config = [
            'response_type' => 'array'
        ];

        // 处理配置
        //获取网站信息  start
        $website = setRedis::getCache(session("website"),'info');
        if (empty($website)) {
            $website = SystemWebsite::where("website_ident",session("website"))->find();
            if ($website) $website = $website->toArray();
            setRedis::setCache(session("website"),"info",$website,0);
        }
        //获取网站信息  end
        $this->info['type'] = $info['type'];
        if ($info['type'] == 'moblie') {
            $config['app_id'] = isset($website['public_platform_appid']) ? $website['public_platform_appid'] : '';
            $config['secret'] = isset($website['public_platform_secrt']) ? $website['public_platform_secrt'] : '';
        }else{
            $config['app_id'] = isset($website['open_platform_appid']) ? $website['open_platform_appid'] : '';
            $config['secret'] = isset($website['open_platform_secrt']) ? $website['open_platform_secrt'] : '';
        }

        self::$instance = Factory::officialAccount($config);
    }

    public function auth ($url)
    {
        if ($this->info['type'] == 'moblie') {
            $response = self::$instance->oauth->scopes(['snsapi_userinfo'])->redirect($url);
        }else{
            $response = self::$instance->oauth->scopes(['snsapi_login'])->redirect($url);
        }
        return $response;
    }

    public function userinfo ()
    {
        $user  = self::$instance->oauth->user();
        return $user;
    }




}
